package com.xinchuang.service.targetSystem.Impl.weapon;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultEnum;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.mapper.targetSystem.SystemTypeMapper;
import com.xinchuang.mapper.targetSystem.weapon.WeaponHouseMapper;
import com.xinchuang.entity.targetSystem.object.SpecialAdd;
import com.xinchuang.entity.targetSystem.target.SystemType;
import com.xinchuang.entity.targetSystem.weapon.WeaponAttribute;
import com.xinchuang.entity.targetSystem.weapon.WeaponMessage;
import com.xinchuang.entity.targetSystem.weapon.WeaponRelation;
import com.xinchuang.entity.targetSystem.weapon.WeaponType;
import com.xinchuang.service.targetSystem.KnowService;
import com.xinchuang.service.targetSystem.weapon.WeaponHouseService;
import com.xinchuang.util.FileElseUtil;
import com.xinchuang.util.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName WeaponHouseServiceImpl
 * @Description: TODO(写一段描述的话)
 * @Author zhangxuan
 * @Date 2022-08-17 15:02
 * @Verion V1.0
 */
@Service
public class WeaponHouseServiceImpl implements WeaponHouseService {

    @Autowired
    private WeaponHouseMapper weaponHouseMapper;

    @Autowired
    private SystemTypeMapper systemTypeMapper;

    @Autowired
    private KnowService knowService;

    private SnowflakeIdWorker snow = new SnowflakeIdWorker(0, 0);

    @Override
    public Result<List<Map<String, Object>>> selectType() {
        List<WeaponType> list = weaponHouseMapper.findTreeAll();
        if (CollectionUtil.isEmpty(list)) {
            return ResultUtil.success("查询成功", new ArrayList<>());
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> map = null;
        for (WeaponType weaponType : list) {
            map = new HashMap<>();
            map.put("typeId", weaponType.getTypeId());
            map.put("typeName", weaponType.getTypeName());
            resultList.add(map);
        }
        return ResultUtil.success("查询成功", resultList);
    }

    @Override
    public Result addOrUpdateType(WeaponType weaponType) {
        if (StringUtils.isBlank(weaponType.getTypeName())) {
            return ResultUtil.error(400, "名称不能为空");
        }
        if (StringUtils.isBlank(weaponType.getTypeId()) || weaponType.getTypeId().equals("0")) {
            weaponType.setTypeId(snow.nextId() + "");
            weaponType.setParentId("1");
            weaponType.setLevel("1");
            weaponHouseMapper.addType(weaponType);
        } else {
            weaponHouseMapper.updateType(weaponType);
        }
        return ResultUtil.success();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result delType(String typeId) {
        //删除关联的武器库
        List<WeaponRelation> weaponRelations = weaponHouseMapper.selectWeaponTargetRelationByTypeId(typeId);
        if (CollectionUtil.isNotEmpty(weaponRelations)) {
            for (WeaponRelation weaponRelation : weaponRelations) {
                //清理分析中使用的数据
                knowService.deleteSubTargetValue(weaponRelation.getId());
            }
            //最终删除关联数据
            weaponHouseMapper.delWeaponTargetRelationByTypeId(typeId);
        }
        List<SystemType> systemTypes = systemTypeMapper.selectSystemTypeByTypeIdList(typeId, 3);
        if (CollectionUtil.isNotEmpty(systemTypes)) {
            //清理关联数据
            for (SystemType systemType : systemTypes) {
                weaponHouseMapper.delWeaponMessageByRelationId(systemType.getId());
            }
            //删除关联数据
            systemTypeMapper.deleteSystemTypeByTypeId(typeId);
        }
        //清理关联数据
        weaponHouseMapper.delWeaponAttributeByRelationId(typeId);
        //删除类型
        weaponHouseMapper.delType(typeId);
        return  ResultUtil.success("删除成功", null);
    }

    @Override
    public Result selectWeaponAttribute(Integer pageNum, Integer pageSize, String typeId) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isBlank(typeId)) {
            resultMap.put("commonList", new ArrayList<>());
            return ResultUtil.success("查询成功", resultMap);
        }
        if (typeId.contains("[")) {
            List stringTransitionList = FileElseUtil.getStringTransitionList(typeId);
            typeId = stringTransitionList.get(stringTransitionList.size() - 1).toString();
        }
        if (pageNum == null || pageSize == null) {
            List<WeaponAttribute> list = weaponHouseMapper.findWeaponByTypeId(typeId);
            List<Object> lists = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(list)) {
                for (WeaponAttribute weaponAttribute : list) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", weaponAttribute.getId());
                    map.put("keyName", weaponAttribute.getKeyName());
                    map.put("key", weaponAttribute.getKey());
                    map.put("keyType", weaponAttribute.getKeyType());
                    map.put("showType", weaponAttribute.getShowType());
                    map.put("required", weaponAttribute.getRequired());
                    map.put("info", weaponAttribute.getInfo());
                    map.put("dataRange", weaponAttribute.getDataRange());
                    map.put("enumerator", FileElseUtil.getStringTransitionList(weaponAttribute.getEnumerator()));
                    map.put("row", weaponAttribute.getRow());
                    map.put("message", weaponAttribute.getMessage());
                    map.put("min", weaponAttribute.getMin());
                    map.put("max", weaponAttribute.getMax());
                    map.put("verify", weaponAttribute.getVerify());
                    lists.add(map);
                }
            }
            resultMap.put("commonList", lists);
            return ResultUtil.success("查询成功", resultMap);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<WeaponAttribute> list = weaponHouseMapper.findWeaponByTypeId(typeId);
        PageInfo<WeaponAttribute> pageInfo = new PageInfo<>(list);
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            List<Object> lists = new ArrayList<>();
            for (WeaponAttribute weaponAttribute : pageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", weaponAttribute.getId());
                map.put("keyName", weaponAttribute.getKeyName());
                map.put("key", weaponAttribute.getKey());
                map.put("keyType", weaponAttribute.getKeyType());
                map.put("showType", weaponAttribute.getShowType());
                map.put("required", weaponAttribute.getRequired());
                map.put("info", weaponAttribute.getInfo());
                map.put("dataRange", weaponAttribute.getDataRange());
                map.put("enumerator", FileElseUtil.getStringTransitionList(weaponAttribute.getEnumerator()));
                map.put("row", weaponAttribute.getRow());
                map.put("message", weaponAttribute.getMessage());
                map.put("min", weaponAttribute.getMin());
                map.put("max", weaponAttribute.getMax());
                map.put("verify", weaponAttribute.getVerify());
                lists.add(map);
            }
            resultMap.put("commonList", lists);
        } else {
            resultMap.put("commonList", new ArrayList<>());
        }
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result addOrUpdateWeaponAttribute(SpecialAdd specialAdd) {
        if (StringUtils.isBlank(specialAdd.getId()) || specialAdd.equals("0")) {
            List<WeaponAttribute> list = weaponHouseMapper.findWeaponByTypeId(specialAdd.getTypeId());
            if (CollectionUtil.isNotEmpty(list)) {
                for (WeaponAttribute weaponAttribute : list) {
                    if (weaponAttribute.getKeyName().equals(specialAdd.getKeyName())) {
                        return ResultUtil.error(ResultEnum.COMMON_KEY_NAME_EXIST);
                    }
                    if (weaponAttribute.getKey().equals(specialAdd.getKey())) {
                        return ResultUtil.error(ResultEnum.COMMON_KEY_EXIST);
                    }
                }
            }
            specialAdd.setId(snow.nextId() + "");
            WeaponAttribute attribute = FileElseUtil.getWeaponAttributeByAdd(specialAdd);
            Integer maxSort = weaponHouseMapper.getWeaponMaxSort(specialAdd.getTypeId());
            if (null == maxSort) {
                maxSort = 0;
            }
            attribute.setSort(maxSort + 1);
            weaponHouseMapper.addWeapon(attribute);
        } else {
            List<WeaponAttribute> list = weaponHouseMapper.findWeaponByTypeId(specialAdd.getTypeId());
            if (CollectionUtil.isNotEmpty(list)) {
                for (WeaponAttribute attribute : list) {
                    if (!specialAdd.getId().equals(attribute.getId()) && attribute.getKeyName().equals(specialAdd.getKeyName())) {
                        return ResultUtil.error(ResultEnum.COMMON_KEY_NAME_EXIST);
                    }
                    if (!specialAdd.getId().equals(attribute.getId()) && attribute.getKey().equals(specialAdd.getKey())) {
                        return ResultUtil.error(ResultEnum.COMMON_KEY_EXIST);
                    }
                }
            }
            weaponHouseMapper.updateWeapon(FileElseUtil.getWeaponAttributeByAdd(specialAdd));
        }
        return ResultUtil.success();
    }

    @Override
    public Result delWeaponAttribute(String id) {
        if (StringUtils.isBlank(id)) {
            return ResultUtil.error(ResultEnum.DELETE_EMPTY);
        }
        weaponHouseMapper.delWeapon(id);
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result getWeaponSort(String id, int sign) {
        WeaponAttribute special = weaponHouseMapper.findWeaponById(id);
        if (null != special) {
            Map<String, Object> map = null;
            switch (sign) {
                case 1:
                    map = weaponHouseMapper.getMin(special.getTypeId());
                    if (null == map || map.get("id").equals(special.getId())) {
                        return ResultUtil.error(500, "已经上移到最顶");
                    } else {
                        weaponHouseMapper.updateWeaponSort(special.getId(), 1);
                        int count = 2;
                        List<String> list = weaponHouseMapper.findWeaponSort(special.getTypeId());
                        for (String str : list) {
                            if (str.equals(special.getId())) {
                                continue;
                            }
                            weaponHouseMapper.updateWeaponSort(str, count);
                            count++;
                        }
                    }
                    break;
                case 2:
                    map = weaponHouseMapper.getUp(special.getSort(), special.getTypeId());
                    if (null == map || map.get("id").toString().equals(special.getId())) {
                        return ResultUtil.error(500, "已经上移到最顶");
                    } else {
                        weaponHouseMapper.updateWeaponSort(special.getId(), (Integer) map.get("sort"));
                        weaponHouseMapper.updateWeaponSort(map.get("id").toString(), special.getSort());
                    }
                    break;
                case 3:
                    map = weaponHouseMapper.getDown(special.getSort(), special.getTypeId());
                    if (null == map) {
                        return ResultUtil.error(500, "已经下移到最底");
                    } else {
                        weaponHouseMapper.updateWeaponSort(special.getId(), (Integer) map.get("sort"));
                        weaponHouseMapper.updateWeaponSort(map.get("id").toString(), special.getSort());
                    }
                    break;
                case 4:
                    map = weaponHouseMapper.getMax(special.getTypeId());
                    if (null == map || map.get("id").equals(special.getId())) {
                        return ResultUtil.error(500, "已经下移到最底");
                    } else {
                        weaponHouseMapper.updateWeaponSort(special.getId(), weaponHouseMapper.getWeaponMaxSort(special.getTypeId()) + 1);
                    }
                    break;
            }
            return ResultUtil.success("操作成功", null);
        }
        return ResultUtil.error(ResultEnum.TYPE_EMPTY);
    }

    @Override
    public Result selectTypePull() {
        List<WeaponType> list = weaponHouseMapper.findTreeAllByParentId("1");
        if (CollectionUtil.isNotEmpty(list)) {
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (WeaponType weaponType : list) {
                Map<String, Object> parent = new HashMap<>();
                parent.put("value", weaponType.getTypeId());
                parent.put("label", weaponType.getTypeName());
                resultList.add(parent);
            }
            return ResultUtil.success("查询成功", resultList);
        }
        return ResultUtil.success(new ArrayList<>());
    }

    @Override
    public Result selectWeaponMessage(String id) {
        SystemType systemType = systemTypeMapper.selectSystemTypeOnly(id);
        if (ObjectUtil.isNotNull(systemType)) {
            Map<String, Object> resultMap = new HashMap<>();
            List<WeaponMessage> list = weaponHouseMapper.selectWeaponMessageAll(id);
            if (CollectionUtil.isNotEmpty(list)) {
                List<Object> data = null;
                for (WeaponMessage weaponMessage : list) {
                    data = new ArrayList<>();
                    data.add(weaponMessage.getKeyValue());
                    data.add(weaponMessage.getRemark());
                    resultMap.put(weaponMessage.getKey(), data);
                }
            }
            return ResultUtil.success(resultMap);
        }
        return ResultUtil.error(500, "当前武器库信息已被删除，请重新选择");
    }

    @Override
    public Result addOrUpdateWeaponMessage(String id, List<WeaponMessage> list) {
        weaponHouseMapper.delWeaponMessageByRelationId(id);
        for (WeaponMessage weaponMessage : list) {
            weaponMessage.setId(snow.nextId() + "");
            weaponMessage.setRelationId(id);
        }
        weaponHouseMapper.addOrUpdateWeaponMessageAll(list);
        return ResultUtil.success();
    }

    @Override
    public Result selectWeaponMessagePull(String typeId) {
        List<SystemType> list = systemTypeMapper.selectSystemTypeByTypeIdList(typeId, 3);
        if (CollectionUtil.isNotEmpty(list)) {
            List<Map<String, Object>> resultList = new ArrayList<>(list.size());
            Map<String, Object> map = null;
            for (SystemType systemType : list) {
                map = new HashMap<>();
                map.put("label", systemType.getTypeName());
                map.put("value", systemType.getId());
                resultList.add(map);
            }
            return ResultUtil.success(resultList);
        }
        return ResultUtil.success(new ArrayList<>());
    }

    @Override
    public Result addWeaponData(WeaponRelation weaponRelation) {
        if (StringUtils.isBlank(weaponRelation.getTargetId())) {
            return ResultUtil.error(400, "关联数据不能为空");
        }
        if (StringUtils.isBlank(weaponRelation.getId()) || weaponRelation.getId().equals("0")) {
            weaponRelation.setId(snow.nextId() + "");
            weaponHouseMapper.addWeaponTargetRelation(weaponRelation);
        } else {
            weaponHouseMapper.updateWeaponTargetRelation(weaponRelation);
        }
        return ResultUtil.success();
    }

    @Override
    public Result delWeaponData(String id) {
        int relation = weaponHouseMapper.delWeaponTargetRelation(id);
        if (relation > 0) {
            return ResultUtil.success("删除成功", null);
        }
        return ResultUtil.error(400, "已被删除/删除的数据不存在");
    }

    @Override
    public Result selectWeaponMessageByWeaponId(String id) {
        WeaponRelation relation = weaponHouseMapper.selectWeaponTargetRelationOnly(id);
        if (ObjectUtil.isNotNull(relation)) {
            List<WeaponMessage> list = weaponHouseMapper.selectWeaponMessageAll(relation.getWeaponId());
            if (CollectionUtil.isNotEmpty(list)) {
                List<Map<String, Object>> resultList = new ArrayList<>();
                Map<String, Object> map = null;
                for (WeaponMessage weaponMessage : list) {
                    if (StringUtils.isNotBlank(weaponMessage.getKeyValue())) {
                        map = new HashMap<>();
                        map.put("name", weaponMessage.getKeyName());
                        map.put("value", weaponMessage.getKeyValue());
                        resultList.add(map);
                    }
                }
                return ResultUtil.success(resultList);
            }
        }
        return ResultUtil.success(new ArrayList<>());
    }

    @Override
    public Result selectWeaponData(String id) {
        Map<String, Object> resultMap = new HashMap<>();
        WeaponRelation relation = weaponHouseMapper.selectWeaponTargetRelationOnly(id);
        if (ObjectUtil.isNotNull(relation)) {
            resultMap.put("id", relation.getId());
            resultMap.put("typeId", relation.getTypeId());
            resultMap.put("weaponId", relation.getWeaponId());
            resultMap.put("position", FileElseUtil.getStringTransitionList(relation.getPosition()));
            resultMap.put("angle", relation.getRemark());
        }
        return ResultUtil.success(resultMap);
    }


}